'''
Created on 29.01.2011

@author: bstar
'''
from dopplershift.core.containers.mediator import getMediator
import urllib

class ParameterInfo:
    def __init__(self, key='', value='', default='1'):
        self._key = key
        self._value = value
        self._default = default
    def getPair(self, matched_params):
        if self._value not in matched_params:
            return self._key, self._default
        return self._key, matched_params.get(self._value)

class CallInfo:
    def __init__(self, id, node_name, upstream, service, excepting=None, caching=False, 
                 caching_time=0, params=None, matching=None, data_content_type = None):
        self._id = id
        self._node_name = node_name
        self._upstream = upstream
        self._service = service
        self._excepting = set()
        if excepting != None:
            self._excepting.update([int(el) for el in excepting.split(',')])
        self._caching= caching
        self._caching_time = int(caching_time)
        cfg = getMediator().get('CollectorConfig')
        self._call_url = '%s/%s'%(cfg.get_upstream(self._upstream),self._service)
        self._params = params
        self._matching = matching
        self.data_content_type = data_content_type
    def getUrl(self, url_params, request_params=None, base_args=None):
        call_url = self._call_url
        matching = dict(map(lambda x: x.getPair(url_params), self._matching))
        
        
        matching.update(url_params)
        for param_key, param_value in matching.iteritems():
            call_url= call_url.replace("{%s}"%param_key, urllib.quote(param_value.encode('utf-8')))
        parameters = map(lambda x: x.getPair(url_params), self._params)
        if base_args: 
            parameters += base_args
        return urllib.basejoin(call_url,"?%s"%urllib.urlencode(parameters))
    def updateUrl(self, call_url, request_params=None):
        if request_params != None:
            for param_key, param_value in request_params.iteritems():
                call_url = call_url.replace("{GET_%s}"%urllib.quote(param_key), urllib.quote(param_value))
        return call_url
    def getNodeName(self):
        return self._node_name
    def getExcepting(self):
        return self._excepting
    def getCachingTime(self):
        return self._caching_time
    def isCaching(self):
        if self._caching == True: return True
        return False
    def getID(self):
        return self._id
    def exception(self, status_code):
        if int(status_code) in self._excepting: return True
        return False

    